# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '52288666': {
        # 支付宝2.6%（1--5000）dwc
        # 银联快捷 1.3% 10-3000 dwc
        'API_KEY': '2$gmaxd%*e6qwn1wj2tf9pn2m8qxjglx',
        'gateway': 'https://api.cyingzf.com/api/apipay',
        'query_gateway': 'https://api.cyingzf.com/api/query',
    },
    '52888790': {
        # 支付宝2.6%（1--5000）tt
        # 银联快捷 1.3% 10-3000 tt
        'API_KEY': '1ok3jrfkvv2q&&izw+tinl%y3ad866d710c64105bf07c6e8fabfdf44',
        'gateway': 'https://api.cyingzf.com/api/apipay',
        'query_gateway': 'https://api.cyingzf.com/api/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_pay_type(service):
    if service == 'alipay':
        return '200'
    elif service == 'unionpayh5':
        return '220'
    elif service == 'unionpayscan':
        return '320'


def _get_bank_type(service):
    if service == 'alipay':
        return '6003'
    elif service == 'unionpayh5':
        return '8003'
    elif service == 'unionpayscan':
        return '8002'


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'appsecret={}'.format(key)
    s = s.lower()
    m = hashlib.sha1()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_query_sign(parameter, key):
    parameter['customCode'] = parameter['custmCode']
    parameter.pop('custmCode')
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'appsecret={}'.format(key)
    s = s.lower()
    m = hashlib.sha1()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("chuangyingpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    """ 创建订单 """
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('interfaceNo', _get_pay_type(service)),
        ('customOrderNo', str(pay.id)),
        ('custmCode', app_id),
        ('money', str(int(pay_amount))),
        ('bankCode', _get_bank_type(service)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    parameter_dict['notifyUrl'] = '{}/pay/api/{}/chuangyingpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH,
                                                                          app_id)
    _LOGGER.info("chuangyingpay create  data: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['customOrderNo'])
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=3,
                             verify=False)
    _LOGGER.info("chuangyingpay create  response: %s", response.text)
    return {'charge_info': json.loads(response.text)['payUrl']}


# SUCCESS
def check_notify_sign(request, app_id):
    resp = json.loads(request.body)
    api_key = _get_api_key(app_id)
    _LOGGER.info("chuangyingpay notify data: %s, order_is is: %s", resp, resp['customOrderNo'])
    verify_notify_sign(resp, api_key)
    pay_id = resp['customOrderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % resp)
        raise ParamError('chuangyingpay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('chuangyingpay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(resp['payStatus'])
    trade_no = str(resp['platformOrderNo'])
    total_fee = float(resp['money'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    # 1：支付成功，2：未支付
    if trade_status == '1' and int(total_fee) > 0:
        _LOGGER.info('chuangyingpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('custmCode', app_id),
        ('customOrderNo', str(pay_id)),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    parameter_dict['custmCode'] = app_id
    parameter_dict.pop('customCode')
    _LOGGER.info("chuangyingpay query  data: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['customOrderNo'])
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=3,
                             verify=False)
    _LOGGER.info("chuangyingpay query  rsp data: %s", response.text)
    if response.status_code == 200:
        resp = json.loads(response.text)
        trade_status = str(resp['data']['payStatus'])
        trade_no = str(resp['data']['platformOrderNo'])
        total_fee = float(resp['data']['money'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 0：支付处理中, 1:支付成功，2：未支付
        if trade_status == '1':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('chuangyingpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('chuangyingpay data error, status_code: %s', response.status_code)
